package com.yixia.web.controller.system;

import com.yixia.common.constant.Constants;
import com.yixia.common.core.domain.AjaxResult;
import com.yixia.common.core.domain.entity.SysMenu;
import com.yixia.common.core.domain.entity.SysUser;
import com.yixia.common.core.domain.model.LoginBody;
import com.yixia.common.utils.SecurityUtils;
import com.yixia.framework.web.service.SysLoginService;
import com.yixia.framework.web.service.SysPermissionService;
import com.yixia.system.domain.system.vo.RouterVo;

import com.yixia.system.service.system.SysMenuService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Slf4j
@RestController
public class SysLoginController {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private SysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    /*
     * 登录方法，用户名密码登录
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajaxResult = AjaxResult.success();
        String token = loginService.login(loginBody);
        ajaxResult.put(Constants.TOKEN, token);
        return ajaxResult;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        log.info("getInfo执行......");
        /*获取当前角色的信息*/
        /*获取获取Authentication从中获取用户信息*/
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        // 获取角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        /*将获取到的角色集合装入sysUser*/
        // 获取权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", sysUser);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();/*获取当前用户id*/
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);/*查询该用户的菜单*/
        // 根据用户id获取所有的角色信息
        /*将得到的菜单树封装成路由对象*/
        List<RouterVo> routerVos = menuService.buildMenus(menus);
        return AjaxResult.success(routerVos);
    }
}
